package com.kingdee.pda.util;

import android.support.annotation.NonNull;
import android.util.Log;

import com.example.basecommon.http.RxHelper;
import com.example.basecommon.http.rxjava.HttpUtils;
import com.example.basecommon.utils.App;
import com.example.basecommon.utils.ConstantUtil;
import com.kingdee.pda.Api;
import com.vector.update_app.HttpManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * @author：dlj
 * @data：2021/7/22:10:18
 * @des：版本更新HttpManager
 */
public class UpdateVersionUtil implements HttpManager {

    private String TAG = "UpdateVersionUtil====";
    private File mFile;

    @Override
    public void asyncGet(@NonNull String url, @NonNull Map<String, String> params, @NonNull Callback callBack) {

    }

    @Override
    public void asyncPost(@NonNull String url, @NonNull Map<String, String> params, @NonNull Callback callBack) {

    }

    @Override
    public void download(@NonNull String url, @NonNull String path, @NonNull String fileName, @NonNull FileCallback callback) {
        Log.d(TAG, "downloadFile");
        //建立一个文件夹
        mFile = new File(path);
        if (!mFile.exists() || !mFile.isDirectory()) {
            mFile.mkdirs();
        }
        //通过Url得到保存到本地的文件名
        String name = url;
        int index = name.lastIndexOf('/');//一定是找最后一个'/'出现的位置
        if (index != -1) {
            name = name.substring(index);
            mFile = new File(path + name);
        }
        Observer<ResponseBody> observer = new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(final ResponseBody responseBody) {
                Thread mThread = new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        writeFileSDcard(responseBody, mFile, callback);
                    }
                };
                mThread.start();
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "onError=" + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "onComplete");
            }

        };
//        HttpUtils.request(Api.class)
//                .login(ConstantUtil.API_LOGIN, map)
//                .compose(RxHelper.observableIO2Main(App.INSTANCE))
//                .subscribe(observer);
    }

    public void writeFileSDcard(ResponseBody responseBody, File mFile, FileCallback downloadListener) {
        downloadListener.onBefore();
        Log.d(TAG, "writeFileSDcard");
        long currentLength = 0;
        OutputStream os = null;
        InputStream is = responseBody.byteStream();
        long totalLength = responseBody.contentLength();
        Log.d(TAG, "totalLength=" + totalLength);
        try {
            os = new FileOutputStream(mFile);
            int len;
            byte[] buff = new byte[1024];
            while ((len = is.read(buff)) != -1) {
                os.write(buff, 0, len);
                currentLength += len;
                Log.d(TAG, "当前长度: " + currentLength);
                int progress = (int) (100 * currentLength / totalLength);
                Log.d(TAG, "当前进度: " + progress);
                downloadListener.onProgress(currentLength, totalLength);
                if (progress == 100) {
                    downloadListener.onResponse(mFile);
                }
            }
        } catch (FileNotFoundException e) {
            Log.d(TAG, "Exception=" + e.getMessage());
            downloadListener.onError("未找到文件！");
            e.printStackTrace();
        } catch (IOException e) {
            Log.d(TAG, "Exception=" + e.getMessage());
            downloadListener.onError("IO错误！");
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
